<template>
  <div>
    <div class="top-bar">
      <div class="main-container">
        <div class="logo" @click="backHomePage">俊一驾考理论学习系统</div>
        <div v-if="userName" style="float: right">
          <div class="user-info">
            <Icon type="md-contact" size="20" />
            &nbsp{{ userName }}&nbsp&nbsp{{ mobile }}&nbsp&nbsp
          </div>
          <div class="logout">
            <Button
              size="large"
              type="default"
              icon="md-log-out"
              ghost
              @click="Logout"
              >登出</Button
            >
          </div>
        </div>

        <div v-else class="login-button">
          <Button
            size="large"
            type="default"
            icon="ios-log-in"
            ghost
            @click="openLoginModal"
            >登录/注册</Button
          >
        </div>
      </div>
    </div>
    <!--<div class="middle-bar">-->
    <!---->
    <!--</div>-->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive">
        <!-- 这里是会被缓存的视图组件，比如 Home！ -->
      </router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    <div class="layout-footer"></div>
    <!--登录弹框-->
    <Modal v-model="loginModal" width="360" footer-hide>
      <p slot="header" style="display: none">
        <!-- <Icon type="information-circled"></Icon>
        <span>用户登录</span>-->
      </p>
      <Tabs :value="tabValue">
        <TabPane label="登陆" name="name1">
          <div style="text-align: center">
            <Form ref="loginForm" :model="loginForm" :label-width="0">
              <Form-item
                prop="mobile"
                :rules="{
                  required: true,
                  message: '必填,请输入合法手机号',
                  min: 1,
                  max: 11,
                  trigger: 'blur',
                  type: 'string',
                  pattern:
                    /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                }"
              >
                <Input
                  prefix="ios-contact"
                  v-model="loginForm.mobile"
                  max="11"
                  placeholder="请输入手机号"
                ></Input>
              </Form-item>
              <!--<Form-item prop="userName" :rules="{required: true, message: '必填,合法手机号',min:1,max:11, trigger:'blur',type:'string'}">-->
              <!--<Input prefix="ios-contact" v-model="loginForm.userName" max="50"  placeholder="请输入手机号"></Input>-->
              <!--</Form-item>-->
              <Form-item
                prop="password"
                :rules="{
                  required: true,
                  message: '密码必填',
                  min: 1,
                  max: 11,
                  trigger: 'blur',
                  type: 'string',
                }"
              >
                <Input
                  prefix="md-lock"
                  v-model="loginForm.password"
                  max="50"
                  type="password"
                  placeholder="请输入密码"
                ></Input>
              </Form-item>
            </Form>
            <Button
              style="margin-top: 40px"
              size="large"
              class="operate-btn"
              long
              :loading="isLoading"
              @click="submitLogin"
              >登录</Button
            >
          </div>
        </TabPane>
        <TabPane label="注册" name="name2">
          <div style="text-align: center">
            <Form ref="registerForm" :model="registerForm" :label-width="0">
              <Form-item
                prop="mobile"
                :rules="{
                  required: true,
                  message: '必填,请输入合法手机号',
                  min: 1,
                  max: 11,
                  trigger: 'blur',
                  type: 'string',
                  pattern:
                    /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                }"
              >
                <Input
                  v-model="registerForm.mobile"
                  max="11"
                  placeholder="请输入手机号"
                >
                  <Icon slot="prepend" type="ios-contact"></Icon>
                  <Button
                    slot="append"
                    @click="getCode"
                    :disabled="sendMsgDisabled"
                    >{{ smsBtnText }}</Button
                  >
                </Input>
              </Form-item>
              <Form-item
                prop="validate_code"
                :rules="{
                  required: true,
                  message: '验证码必填',
                  min: 1,
                  max: 6,
                  trigger: 'blur',
                  type: 'string',
                }"
              >
                <Input
                  prefix="md-apps"
                  v-model="registerForm.validate_code"
                  max="6"
                  placeholder="请输入收到得验证码"
                ></Input>
              </Form-item>
              <Form-item
                prop="password"
                :rules="{
                  required: true,
                  message: '密码必填',
                  min: 1,
                  max: 11,
                  trigger: 'blur',
                  type: 'string',
                }"
              >
                <Input
                  prefix="md-lock"
                  v-model="registerForm.password"
                  max="50"
                  type="password"
                  placeholder="请输入密码"
                ></Input>
              </Form-item>
            </Form>
            <Button
              size="large"
              class="operate-btn"
              long
              :loading="isLoading"
              @click="submitRegister"
              >注册</Button
            >
          </div>
        </TabPane>
      </Tabs>
    </Modal>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { login, logout, getValidateCode, register } from "@/api/user";
export default {
  data() {
    return {
      loginModal: false,
      btnLoading: false,
      isLoading: false,
      loginForm: {
        mobile: "",
        password: "",
        login_type: 2,
      },
      registerForm: {
        mobile: "",
        password: "",
        validate_code: "",
        purpose: 1,
      },
      time: 120, // 发送验证码倒计时
      sendMsgDisabled: false,
      tabValue: "name1",
    };
  },
  computed: {
    ...mapState({
      isVip: (state) => state.user.isVip,
      userName: (state) => state.user.userName,
      mobile: (state) => state.user.mobile,
      userAvator: (state) => state.user.avatorImgPath,
    }),
    smsBtnText: function () {
      if (this.sendMsgDisabled) {
        return `${this.time}秒后获取`;
      } else {
        return "发送验证码";
      }
    },
  },
  created() {
    this.$store.commit("updateUserState");
    this.$store.commit("setCurrentSubject");
  },
  methods: {
    openLoginModal() {
      this.loginModal = true;
    },
    backHomePage() {
      this.$router.push({
        name: "home",
      });
    },
    async Logout() {
      let result = await logout({});
      if (result.status === 0) {
        sessionStorage.clear();
        this.$Message.success("登出成功!");
        this.$store.commit("updateUserState");
        this.$router.push({
          name: "home",
        });
      } else {
        this.$Message.error("服务器异常,稍后再试");
      }
    },
    async submitLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.loginForm));
          this.isLoading = true;
          this.$Loading.start();
          let result = await login(params);
          console.log(result);
          if (result.status === 0) {
            this.isLoading = false;
            this.$Loading.finish();
            this.$Message.success("登录成功!");
            this.loginModal = false;
            this.$store.commit("handleLogin", result.data);
            //            this.$router.push({
            //              name: 'home'
            //            })
          } else {
            this.isLoading = false;
            this.$Loading.error();
            this.$Message.error(result.msg);
          }
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
    countDown() {
      let me = this;
      me.sendMsgDisabled = true;
      let interval = window.setInterval(function () {
        if (me.time-- <= 0) {
          me.time = 60;
          me.sendMsgDisabled = false;
          window.clearInterval(interval);
        }
      }, 1000);
    },
    async getCode() {
      if (!this.sendMsgDisabled) {
        if (/^[1][0-9]{10}$/.test(this.registerForm.mobile)) {
          let result = await getValidateCode({
            mobile: this.registerForm.mobile,
            purpose: 1,
          });
          if (result.status === 0) {
            this.countDown();
          } else {
            this.$Message.error("服务器异常,稍后再试");
          }
        } else {
          this.$Message.error("请输入正确的手机号");
        }
      }
    },
    async submitRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.registerForm));
          this.isLoading = true;
          let result = await register(params);
          console.log(result);
          if (result.status === 0) {
            this.isLoading = false;
            this.tabValue = "name1";
            this.$Message.success("注册成功，请登陆!");
          } else {
            this.isLoading = false;
            this.$Message.error(result.msg);
          }
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
@import "./../assets/styles/common";
@import "Main.less";
.ivu-btn-ghost.ivu-btn-dashed:hover,
.ivu-btn-ghost.ivu-btn-default:hover {
  color: #e5e9fd;
  border-color: #e5e9fd;
}

.ivu-modal-header {
  padding: 0;
}
</style>
